package com.zjw.register.service;

import com.zjw.model.R;
import com.zjw.model.enums.ClientType;
import com.zjw.model.enums.NotifyType;
import com.zjw.model.pojo.vo.WsNodeInfo;
import com.zjw.model.pojo.vo.WsNotifyVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class RegisterService {

    private final static Logger log = LoggerFactory.getLogger(RegisterService.class);

    /**
     * 存储用户与服务器的关系: groupId-userId-clientType-server
     */
    private Map<String, Map<String, Map<ClientType, WsNodeInfo>>> registerMap = new ConcurrentHashMap<>();

    public R<Void> register(WsNotifyVO notifyVO) {
        log.info("register: {}", notifyVO);
        String groupId = notifyVO.getGroupId();
        String userId = notifyVO.getUserId();
        ClientType clientType = notifyVO.getClientType();
        NotifyType notifyType = notifyVO.getNotifyType();
        Map<ClientType, WsNodeInfo> user = getUserAllServer(groupId, userId);
        if (NotifyType.ONLINE.equals(notifyType)) {
            WsNodeInfo nodeInfo = new WsNodeInfo();
            nodeInfo.setIp(notifyVO.getIp());
            nodeInfo.setPort(notifyVO.getPort());
            nodeInfo.setClientType(clientType);
            user.put(clientType, nodeInfo);
            return R.ok();
        }
        user.remove(clientType);
        return R.ok();
    }

    public R<Collection<WsNodeInfo>> getServersByUserId(String groupId, String userId) {
        log.info("getServersByUserId: groupId={}, userId={}", groupId, userId);
        Map<ClientType, WsNodeInfo> user = getUserAllServer(groupId, userId);
        return R.ok(user.values());
    }

    public R<WsNodeInfo> getServerByClientType(String groupId, String userId, ClientType clientType) {
        log.info("getServerByClientType: groupId={}, userId={}, clientType={}", groupId, userId, clientType);
        Map<ClientType, WsNodeInfo> user = getUserAllServer(groupId, userId);
        return R.ok(user.get(clientType));
    }

    private Map<ClientType, WsNodeInfo> getUserAllServer(String groupId, String userId) {
        registerMap.putIfAbsent(groupId, new ConcurrentHashMap<>());
        Map<String, Map<ClientType, WsNodeInfo>> group = registerMap.get(groupId);
        group.putIfAbsent(userId, new ConcurrentHashMap<>());
        return group.get(userId);
    }

    public R<Map<String, Map<String, Map<ClientType, WsNodeInfo>>>> getServers() {
        return R.ok(registerMap);
    }
}
